import Toast from '@vant/weapp/toast/toast'
import { authorization } from '../../../../utils/location'
const app = getApp()
Page({
    data: {
        customerTagOptions: [
            { text: '新客户', value: 'new' },
            { text: '老客户', value: 'old' },
            { text: '潜在客户', value: 'potential' }
        ],
        customer: ['重点客户', 'VIP客户', '一般客户', '无价值客户', '沉默客户'],
        orderPlatformOptions: [
            { label: '淘宝', value: 'taobao', checked: false },
            { label: '京东', value: 'jd', checked: false },
            { label: '拼多多', value: 'pdd', checked: false }
        ],
        showPicker: false,
        popupFlag: false,
        customer_mobile: '',
        customer_type: '',
        result: [],
        otherInputValue: '',
        showOtherInput: false,
        selectedDate: '',
        showDatePicker: false,
        platform_difference: '',
        tempFilePaths: [],
        longitude: '',
        latitude: '',
        customer_name: '',
        customer_mobile: '',
        customer_remarks: '',
        customer_type: '',
        access_token: '',

    },
    onLoad(options) {
        let access_token = app.session.access_token || wx.getStorageSync('access_token')
        console.log(access_token)
        this.setData({
            access_token,
        })
    },
    // 显示日期选择器弹窗
    showPickerPopup() {
        this.setData({
            showPicker: true
        });
    },
    // 关闭日期选择器弹窗
    onDatePickerClose() {
        this.setData({
            showDatePicker: false
        });
    },
    // 处理 picker 选择变化

    onpickeCancel() {
        this.setData({
            showDatePicker: false
        });

    },
    onpickerConfirm(event) {
        const { picker, value, index } = event.detail;
        console.log(value)
        this.setData({
            showPicker: false,
            customer_type: value
        });
    },
    // 复选框选择变化事件处理函数
    ontypeChange(e) {
        const value = e.detail;
        this.setData({
            result: value,
            // 若选择结果包含“其他”，显示输入框
            showOtherInput: value.includes('其他')
        });
    },
    // 其他输入框输入事件处理函数
    onOtherInputChange(e) {
        this.setData({
            otherInputValue: e.detail
        });
    },

    onDateConfirm(event) {
        console.log(event);
        const value = event.detail;
        // 格式化日期的函数
        const formatDate = (date) => {
            const year = date.getFullYear();
            const month = String(date.getMonth() + 1).padStart(2, '0');
            const day = String(date.getDate()).padStart(2, '0');
            return `${year}/${month}/${day}`;
        };
        // 对获取到的日期进行格式化
        const formattedDate = formatDate(new Date(value));
        console.log(formattedDate);
        this.setData({
            showDatePicker: false,
            selectedDate: formattedDate
        });
    },
    showDatePickerPopup() {
        this.setData({
            showDatePicker: true
        });
    },


    onDateClose() {
        console.log("关闭")
        this.setData({
            showDatePicker: false
        });
    },
    onPlatChange(e) {
        const platform_difference = e.detail;
        // 清除之前的定时器
        this.setData({
            platform_difference
        });
    },
    /**
   * 获取当前位置
   */
    async get_current_location() {
        let res = await authorization()
        console.log("authorization res", res);
        this.setData({
            longitude: res.longitude,
            latitude: res.latitude
        })
    },
    // 格式化时间的方法
    async afterRead(event) {
        let that = this
        const { file } = event.detail;
        console.log(event)
        console.log(this.data.tempFilePaths)
        // 获取当前位置
        await this.get_current_location();
        // 获取当前时间
        const now = new Date();
        const year = now.getFullYear();
        const month = String(now.getMonth() + 1).padStart(2, '0');
        const day = String(now.getDate()).padStart(2, '0');
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        const seconds = String(now.getSeconds()).padStart(2, '0');
        const currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
        // 获取位置信息
        console.log(currentTime)
        const { longitude, latitude } = this.data;
        // 获取定位信息
        let address = '';
        if (longitude && latitude) {
            try {
                const res = await new Promise((resolve, reject) => {
                    wx.request({
                        url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=ANNBZ-KHK35-WPKIX-I2FVZ-PLPI2-RYB6J`,
                        success: (res) => {
                            if (res.data.status === 0) {
                                resolve(res.data.result.address);
                            } else {
                                reject(new Error('逆地理编码失败'));
                            }
                        },
                        fail: (err) => {
                            reject(err);
                        }
                    });
                });
                address = res;
            } catch (err) {
                console.error('获取位置信息失败', err);
            }
        }
        // 创建 canvas 上下文
        const ctx = wx.createCanvasContext('watermarkCanvas');
        // 绘制图片
        ctx.drawImage(file.url, 0, 0, 300, 300);
        // 设置水印文字样式
        ctx.setFontSize(14);
        ctx.setFillStyle('rgba(255, 255, 255, 0.8)');
        // 添加位置水印
        if (address) {
            ctx.fillText(`地址: ${address}`, 10, 260);
        }
        // 添加时间水印
        ctx.fillText(`时间: ${currentTime}`, 10, 280);
        // 绘制到 canvas
        ctx.draw(false, () => {
            // 将 canvas 转换为临时文件路径
            wx.canvasToTempFilePath({
                canvasId: 'watermarkCanvas', // 光标处插入代码
                success: (res) => {
                    const watermarkedFile = { url: res.tempFilePath };
                    that.setData({
                        tempFilePaths: [...that.data.tempFilePaths, watermarkedFile]
                    });

                    // 上传带水印的图片
                    wx.uploadFile({
                        url: 'https://helper.fuduoduoshop.com/api/v1/file/images',
                        filePath: watermarkedFile.url,
                        header: {
                            'Content-Type': 'application/json',
                            'x-api-key': that.data.access_token
                        },
                        name: 'file',
                        formData: {
                            drive: 'qiniu',
                            thumb: JSON.stringify([
                                {
                                    width: 100,
                                    height: 100
                                }
                            ])
                        },
                        success: (res) => {
                            let response = JSON.parse(res.data);
                            let code = response.code;
                            if (code === 200) {
                                const { tempFilePaths = [] } = that.data;
                                tempFilePaths.push({ ...watermarkedFile, url: response.data.url });
                                that.setData({
                                    tempFilePaths
                                });
                            }
                        }
                    });
                },
                fail: (err) => {
                    console.error('生成带水印图片失败', err);
                    // 若失败，上传原始图片
                    Toast('生成带水印图片失败~')
                }
            });
        });
    },
    imgDelete(event) {
        console.log("删除图片")
        let that = this
        let urlPath = event.detail.file.url
        wx.request({
            url: app.globalData.API + '/delivery/index/delete-qiniu-image',
            header: {
                'Content-Type': 'application/json',
                'x-api-key': that.data.access_token
            },
            data: {
                path: urlPath
            },
            method: 'POST',
            success: res => {
                if (res.data.code == 200) {
                    console.log(res)
                    const success = res.data.data
                    console.log(success)
                    if (success) {
                        let tempFilePaths = that.data.tempFilePaths
                        tempFilePaths = tempFilePaths.filter(item => item.url !== urlPath)
                        that.setData({
                            tempFilePaths
                        })
                    }
                }
            }
        })
    },
    formSubmit(e) {
        const {
            search_mobile,
            customer_name,
            customer_mobile,
            customer_remarks,
            customer_type,
            result,
            otherInputValue,
            selectedDate,
            platform_difference,
            tempFilePaths
        } = this.data;
        // 收集表单数据
        const formData = {
            search_mobile,
            customer_name,
            customer_mobile,
            customer_remarks,
            customer_type,
            result,
            otherInputValue,
            selectedDate,
            platform_difference,
            // 提取图片 URL 数组
            tempFilePaths: tempFilePaths.map(file => file.url)

        };
        // 发送请求到后台
        wx.request({
            url: 'https://your-api-url.com/submit-order', // 替换为实际的后台接口地址
            method: 'POST',
            header: {
                'Content-Type': 'application/json',
                'x-api-key': this.data.access_token // 确保 access_token 存在于 data 中
            },
            data: formData,
            success: (res) => {
                if (res.data.code === 200) {
                    wx.showToast({
                        title: '提交成功',
                        icon: 'success'
                    });
                    // 可添加提交成功后的其他操作，如跳转页面
                } else {
                    wx.showToast({
                        title: '提交失败',
                        icon: 'none'
                    });
                }
            },
            fail: (err) => {
                console.error('请求失败:', err);
                wx.showToast({
                    title: '网络请求失败',
                    icon: 'none'
                });
            }
        });
    }
});